<?php
include_once '../PHP/autoinclude.php';
/**
 * This file is being used to simulate users, it extracts the information out the files and parses them and process them
 */

/**
 * Prepares an input to be parsed to a JSON format
 * @param type $input
 * @return type 
 */
function prepareJSON($input) {

    //This will convert ASCII/ISO-8859-1 to UTF-8.
    //Be careful with the third parameter (encoding detect list), because
    //if set wrong, some input encodings will get garbled (including UTF-8!)
    $imput = mb_convert_encoding($input, 'UTF-8', 'ASCII,UTF-8,ISO-8859-1');

    //Remove UTF-8 BOM if present, json_decode() does not like it.
    if(substr($input, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $input = substr($input, 3);

    return $input;
}

$database=new Database();
$search=new Search();
$root='../../../Test/Simulate/';
if($handle=opendir($root)){
    //for each file
    while(false!==($entry=readdir($handle))){
        $database=new Database();
            //extract the name of the user out of the file name
            $userName= explode(".", $entry);
            $ext=$userName[1];
            $userName=$userName[0];

        if($ext=='json' && $handleU=fopen($root.$entry,"r")){

            //add the user to the database
            $user=new User();
            $user->setUserName($userName);
            $user->setEmail('simulate@email.com');

            $database->newUser($user, 'simulate');
            
            //'log in' the user
            $database->logIn($userName, 'simulate');
            $idUser=$database->getCache('user');
            
            $contents=fread($handleU, filesize($root.$entry));
            $contents=prepareJSON($contents);
            $json=json_decode($contents,true);
            print("USER: ".$userName." id:".$idUser."<br>");
            //loop through all the songs in the file
            for($i=0;$i<count($json['songs'])-1;$i++){
                
                //get the id of the artist
                $artist=$database->getArtistByName($json['songs'][$i]['artistName'], false);
                //if we dont have the artist, artist will be null
                if($artist!=null){
                    print("Artist: ".$json['songs'][$i]['artistName']." track: ".$json['songs'][$i]['songName']."<br>");
                    $idArtist=$artist->getID();
                    //ask for the album of the artist through a webservice call to last.fm
                    $first='http://ws.audioscrobbler.com/2.0/?method=track.getinfo&format=json&api_key=2e0f6a31b6598dae0585ac68964d579c&artist=';
                    $artistNameR=str_replace(' ','%20',$json['songs'][$i]['artistName']);
                    $trackNameR=str_replace(' ','%20',$json['songs'][$i]['songName']);
                    $url=$first.$artistNameR.'&track='.$trackNameR;
                    $html=  file_get_contents($url,true);
                    $jsonLastFM=  json_decode($html,true);
                    
                    if(isset($jsonLastFM['track']['album']['title'])){
                        $albumName=$jsonLastFM['track']['album']['title'];
                        //Check if we already have the album
                        $album=$database->getAlbumByName($albumName, $idArtist);
                        print('Albumname: '.$albumName."<br>");
                        if($album==null){
                            //If we dont have the album, add it to the database
                            $album=new Album();
                            $album->setName($albumName);
                            $track=new Track();
                            $track->setName($json['songs'][$i]['songName']);
                            $album->addTrack($track);
                            $database->newAlbum($album, $idArtist);
                        }
                        else{
                            $track=$database->getTrackByName($json['songs'][$i]['songName'], $album->id());
                            if($track==null){
                                //If we dont have the track, add it to the database
                                $track=new Track();
                                $track->setName($json['songs'][$i]['songName']);
                                $database->newTrack($track, $album->id());
                            }
                        }
                        //get the track id
                        $track=$database->getTrackByName($json['songs'][$i]['songName'], $album->id());
                        $idTrack=$track->id();
                        //Sets the listening count to the database
                        $database->setListening($idArtist, $idTrack);
                    }
                }
            }
            //close the file
            fclose($handleU);
            //log out the user
            $database->logOut();
            print("<br><br>");
        }
    }
    //close the map
    closedir($handle);
}
?>
